package com.itheima.filter;

import com.itheima.bean.Employee;
import com.itheima.bean.User;
import com.itheima.config.BaseContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req= (HttpServletRequest) servletRequest;
        HttpServletResponse resp= (HttpServletResponse) servletResponse;
        String uri = req.getRequestURI();
        if (uri.contains("login.html")) {
            filterChain.doFilter(req, resp);
            return;
        }
        if (uri.contains("login") || uri.contains(".js") || uri.contains("styles") || uri.contains(".ico") || uri.contains("plugins") || uri.contains("getcode")) {
            filterChain.doFilter(req, resp);
            return;
        }
        if (req.getSession().getAttribute("employee") != null) {
            Employee employee = (Employee) req.getSession().getAttribute("employee");
            BaseContext.setThreadLocal(employee.getId());
            filterChain.doFilter(req, resp);
            return;
        }
        if (req.getSession().getAttribute("user") != null) {
            User employee = (User) req.getSession().getAttribute("user");
            BaseContext.setThreadLocal(employee.getId());
            filterChain.doFilter(req, resp);
            return;
        }
        if (uri.contains("backend")) {
            resp.sendRedirect("/backend/page/login/login.html");
            return;
        }
        resp.sendRedirect("/front/page/login.html");
    }
}
